package priv.stones.controller.administrate;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import priv.stones.common.annotation.CommitLog;
import priv.stones.common.utils.Result;
import priv.stones.controller.administrate.shiro.ShiroUtils;
import priv.stones.entity.SysAdmin;
import priv.stones.entity.SysRole;
import priv.stones.service.SysRoleService;

import java.util.Date;
import java.util.List;

/**
 * @Author: Stones
 * @Description:
 * @Date: 2017/10/12 14:46
 */
@Controller
@RequestMapping("/administrate/admin")
public class AdminController extends BaseController {

    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 列表
     *
     * @return
     */
    @RequestMapping("")
    @RequiresPermissions("sys:admin:list")
    public String List(Model model
            , @RequestParam(value = "name", defaultValue = "") String name
            , @RequestParam(value = "pageNo", defaultValue = "1") int pageNo
            , @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        EntityWrapper<SysAdmin> ew = new EntityWrapper<>();
        if (!StringUtils.isBlank(name)) {
            ew.like("name", name);
        }
        ew.ne("name", ShiroUtils.SuperAdmin);
        ew.orderBy("registetime", true);
        Page<SysAdmin> data = sysAdminService.selectPage(new Page<>(pageNo, pageSize), ew);
        model.addAttribute("data", data.getRecords());
        model.addAttribute("name", name);
        model.addAttribute("pageNo", pageNo);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("dataCount", data.getTotal());
        return FreeMarkerViewResult("admin/list", model);
    }

    /**
     * 编辑
     *
     * @param model
     * @return
     */
    @RequestMapping("/edit")
    public String Edit(Model model, @RequestParam(value = "id", defaultValue = "") String id) {
        SysAdmin sysAdmin;
        if (!StringUtils.isBlank(id)) {
            sysAdmin = sysAdminService.selectById(id);
            /*拥有的角色*/
            model.addAttribute("ownRoles", sysAdminService.selectRoleIdsById(id));
        } else {
            sysAdmin = new SysAdmin();
            sysAdmin.setStatus(1);
        }
        model.addAttribute("data", sysAdmin);
        List<SysRole> sysRoleList = sysRoleService.selectList(new EntityWrapper<SysRole>()
                .eq("status", 1)
                .orderBy("createtime", true));
        model.addAttribute("roles", sysRoleList);
        return FreeMarkerViewResult("admin/edit", model);
    }

    /**
     * 添加...密码默认为123456
     *
     * @param sysAdmin
     * @return
     */
    @RequestMapping(value = "/edit/insert", method = RequestMethod.POST)
    @RequiresPermissions("sys:admin:insert")
    @CommitLog("添加管理员")
    @ResponseBody
    public Result Insert(SysAdmin sysAdmin, @RequestParam(value = "roles[]", required = false) String[] roles) {
        sysAdmin.setLoginsalt(RandomStringUtils.randomAlphanumeric(20));
        sysAdmin.setLoginpwd(ShiroUtils.sha256("123456", sysAdmin.getLoginsalt()));
        if (sysAdminService.selectCount(new EntityWrapper<SysAdmin>().eq("name", sysAdmin.getName())) > 0) {
            return Result.Error("用户名已存在");
        }
        if (!StringUtils.isBlank(sysAdmin.getPhone())) {
            if (sysAdminService.selectCount(new EntityWrapper<SysAdmin>().eq("phone", sysAdmin.getPhone())) > 0) {
                return Result.Error("手机已存在");
            }
        } else {
            sysAdmin.setPhone(null);
        }
        sysAdmin.setRegistetime(new Date());
        boolean result = sysAdminService.insert(sysAdmin);
        sysAdminService.relateRoles(roles, sysAdmin.getId());
        return result ? Result.Ok() : Result.Error();
    }

    @RequestMapping(value = "/edit/update", method = RequestMethod.POST)
    @RequiresPermissions("sys:admin:update")
    @CommitLog("修改管理员")
    @ResponseBody
    public Result Update(SysAdmin sysAdmin, @RequestParam(value = "roles[]", required = false) String[] roles) {
        sysAdmin.setName(null);
        if (!StringUtils.isBlank(sysAdmin.getPhone())) {
            if (sysAdminService.selectCount(new EntityWrapper<SysAdmin>().eq("phone", sysAdmin.getPhone()).ne("id", sysAdmin.getId())) > 0) {
                return Result.Error("手机已存在");
            }
        } else {
            sysAdmin.setPhone(null);
        }
        boolean result = sysAdminService.updateById(sysAdmin);
        sysAdminService.relateRoles(roles, sysAdmin.getId());
        return result ? Result.Ok() : Result.Error();
    }

    /**
     * 重置管理员密码
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/resetpwd", method = RequestMethod.POST)
    @RequiresPermissions("sys:admin:resetpwd")
    @CommitLog("重置管理员密码")
    @ResponseBody
    public Result ResetPwd(String id) {
        SysAdmin sysAdmin = new SysAdmin();
        sysAdmin.setId(id);
        sysAdmin.setLoginsalt(RandomStringUtils.randomAlphanumeric(20));
        sysAdmin.setLoginpwd(ShiroUtils.sha256("123456", sysAdmin.getLoginsalt()));
        return sysAdminService.updateById(sysAdmin) ? Result.Ok() : Result.Error();
    }

}
